package com.pansoft.newasset.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.widget.RoundAngleImageView;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.newasset.activity.TotalAssetsActivity;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.TotalAssetBean;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.qmuiteam.qmui.widget.QMUILoadingView;
import com.utilcode.util.SizeUtils;

import com.utilcode.util.ToastUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.manager.MarketExchangeSiteManager.getCurrentMarketSite;

/**
 * 新版资产 -总资产界面
 *
 * @author yqs
 * @date 2019/01/28
 */

public class NewAssetTotalFragment extends BaseFragment implements View.OnClickListener {
    private static final String TAG = "NewAssetTotalFragment";
    private View rootView;
    private TextView tvCurrentPage;
    private TextView tvTotalPage;
    private ViewPager viewpager;
    private List<TotalAssetBean> assetBeans;
    private AssetViewPagerAdapter adapter;
    private TextView tvTips;
    private ImageView ivHint;
    private ImageView ivShowNum;
    private LinearLayout llLoadingOrFail;
    private QMUILoadingView loadView;
    private TextView tvAmount;
    private LinearLayout ll_top;
    private RelativeLayout rl_eyeImage_amount;
    /**
     * 是否显示数据信息的状态
     */
    private boolean isShowNum = Boolean.parseBoolean(EnvironmentVariable.getProperty("asset_show_num", "true"));

    /**
     * 总资产
     */
    String currentTotalPrice;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.new_asset_fragment_total_asset, container, false);
        initView();
        initAdapter();
        requestData();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        isShowNum = Boolean.parseBoolean(EnvironmentVariable.getProperty("asset_show_num", "true"));
        changeEyeImage();
        if (assetBeans != null && assetBeans.size() > 0) {
            for (int i = 0; i < assetBeans.size(); i++) {
                assetBeans.get(i).setShowNum(isShowNum);
            }
            adapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        ((TextView) rootView.findViewById(R.id.tv_title_text)).setText(String
                .format(getString(R.string.open_planet_asset_total_assets),
                        CurrencyAndBourseManager.getCurrencyUnitCode()));
        tvCurrentPage = rootView.findViewById(R.id.tv_current_page);
        tvTotalPage = rootView.findViewById(R.id.tv_total_page);
        viewpager = rootView.findViewById(R.id.viewpager);
        llLoadingOrFail = rootView.findViewById(R.id.ll_loading_or_fail);
        tvTips = rootView.findViewById(R.id.tv_tips);
        llLoadingOrFail.setOnClickListener(this);
        ivHint = rootView.findViewById(R.id.iv_hint);

        tvAmount = rootView.findViewById(R.id.tv_amount);
        ll_top = rootView.findViewById(R.id.ll_top);
        ll_top.setOnClickListener(this);
        loadView = rootView.findViewById(R.id.loadView);

        //是否隐藏数值，默认显示
        ivShowNum = rootView.findViewById(R.id.iv_show_num);
        ivShowNum.setOnClickListener(this);
        rl_eyeImage_amount = rootView.findViewById(R.id.rl_eyeImage_amount);
        changeEyeImage();
    }

    private void changeEyeImage() {
        if (currentTotalPrice == null) {
            currentTotalPrice = "0";
        }
        if (isShowNum) {
            ivShowNum.setImageResource(R.drawable.icon_show_password);
            tvAmount.setText(currentTotalPrice);
        } else {
            ivShowNum.setImageResource(R.drawable.icon_hide_password);
            tvAmount.setText("******");
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ll_loading_or_fail) {
            requestData();
        } else if (v.getId() == R.id.ll_top) {
            //总资产界面
            TotalAssetsActivity.start(getActivity(), "total");
        } else if (v.getId() == R.id.iv_show_num) {
            //保存是否显示数据信息的状态
            saveShowNumStatus(isShowNum = !isShowNum);
            //
            changeEyeImage();
            if (assetBeans != null && assetBeans.size() > 0) {
                for (int i = 0; i < assetBeans.size(); i++) {
                    assetBeans.get(i).setShowNum(isShowNum);
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 保存是否显示数据信息的状态
     */
    private void saveShowNumStatus(boolean isShowNum) {
        EnvironmentVariable.setProperty("asset_show_num", String.valueOf(isShowNum));
    }

    private void initAdapter() {
        assetBeans = new ArrayList<>();
        adapter = new AssetViewPagerAdapter(getActivity(), assetBeans);
        viewpager.setPageMargin(SizeUtils.dp2px(12));
        viewpager.setAdapter(adapter);
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvCurrentPage.setText(position + 1 + "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void requestData() {
        showLoading();
        //刷新时设置总资产金额为空字符
        tvAmount.setText("");
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getUserName());
        //allAccountFollowTrusteeshipCoinList 以前的接口
        //allAccountFollowCoinListExceptBalance 现在的接口为解决接口加载慢的情况 先只请求币的列表，再请求币的余额 数量信息allAccountFollowCoinList()
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/allAccountFollowCoinListExceptBalance", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            disposeRequestData(0, jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                            showError();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        adapter.notifyDataSetChanged();
                        showError();
                    }
                });
    }


    /**
     * 请求代币余额数量信息
     */
    private void allAccountFollowCoinList() {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getUserName());
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/allAccountFollowCoinList", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            disposeRequestData(1, jsonObject);
                        } catch (Exception e) {
                            e.printStackTrace();
                            showError();
                        }
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
    }

    /**
     * 处理请求的JSon数据
     *
     * @param status     0 是处理allAccountFollowCoinListExceptBalance接口请求的数据，没有余额和代币的数量
     *                   1 是处理allAccountFollowCoinList  更新余额和数量
     * @param jsonObject 处理的数据
     */
    private void disposeRequestData(int status, JSONObject jsonObject) {
        JSONArray list = jsonObject.optJSONArray("userFollowTrusteeshipCoin");
        if (jsonObject.optString("result").equals("success")) {
            if (list.length() > 0) {
                if (status == 0) {
                    assetBeans.clear();
                }
                for (int i = 0; i < list.length(); i++) {
                    JSONObject object = list.optJSONObject(i);
                    //代币数量
//                                        String coin = TCMathUtil.retainAsignDecimals(object.optDouble("availableCoin"), 5);
                    String coin = BalanceUtil.formatPrice(object.optDouble("availableCoin"), true, 5);
                    //代笔单价
                    double rate = object.optDouble("coinMarketPrice");
                    String currentRate = BalanceUtil.formatPrice(MarketNumberUtils.
                            getRealPrice(getCurrentMarketSite(),
                                    "CNY",
                                    CurrencyAndBourseManager.getCurrencyUnitCode(),
                                    rate), true, 2);
                    //当前代币总价值
                    double rmbValue = object.optDouble("userCoinMarketNum");
                    double currentValue = MarketNumberUtils
                            .getRealPrice(getCurrentMarketSite(),
                                    "CNY",
                                    CurrencyAndBourseManager.getCurrencyUnitCode(),
                                    rmbValue);
                    String rmb = BalanceUtil.formatPrice(currentValue, true, 2);
                    if (status == 0) {
                        TotalAssetBean assetBean = new TotalAssetBean.Builder()
                                .assetName(object.optString("coinName"))
                                .assetValue(coin)
                                .rmbValue(rmb + " " + CurrencyAndBourseManager.getCurrencyUnitCode())
                                .rate("≈" + currentRate + " " + CurrencyAndBourseManager.getCurrencyUnitCode())
                                .assetIcon(object.optString("coinIcon"))
                                .isShowNum(isShowNum).build();
                        assetBeans.add(assetBean);

                    } else if (status == 1) {
                        if (assetBeans != null && assetBeans.size() > 0) {
                            for (TotalAssetBean assetBean : assetBeans) {
                                if (assetBean.getAssetName().equals(object.optString("coinName"))) {
                                    assetBean.setRmbValue(rmb + " " + CurrencyAndBourseManager.getCurrencyUnitCode());
                                    assetBean.setAssetValue(coin);
                                    assetBean.setRate("≈" + currentRate + " " + CurrencyAndBourseManager.getCurrencyUnitCode());
                                }
                            }
                        }
                    }
                }
                //只有请求列表后才请求代币余额数量信息
                if (status == 0) {
                    //请求代币余额 数量等信息数据
                    allAccountFollowCoinList();
                }
                //更新头部所有的总的人民币值
//                                    String totalPrice = TCMathUtil.retainAsignDecimalsWithZero(jsonObject.optDouble("num"), 2);
                double totalPrice = MarketNumberUtils
                        .getRealPrice(getCurrentMarketSite(),
                                "CNY",
                                CurrencyAndBourseManager.getCurrencyUnitCode(),
                                jsonObject.optDouble("num"));
                currentTotalPrice = BalanceUtil.formatPrice(totalPrice, true, 2);

                tvTotalPage.setText(assetBeans.size() + "");
                // adapter.setTotalPrices(totalPrice);
//                                    tvAmount.setText(currentTotalPrice);
                changeEyeImage();

                if (status == 0) {
//                    if(assetBeans!=null&&assetBeans.size()>0){
//                        for(TotalAssetBean totalAssetBean : assetBeans){
//                            totalAssetBean.setRmbValue("--");
//                            totalAssetBean.setRate("--");
//                            totalAssetBean.setAssetValue("--");
//                            currentTotalPrice = "--";
//                        }
//                    }
                }
                adapter.notifyDataSetChanged();
                showAsset();
                viewpager.setCurrentItem(0);
                tvCurrentPage.setText("1");

            } else {
                if(status == 0){
                    showEmptyAsset();
                }else {
                    ToastUtils.showShort(_mActivity.getString(R.string.common_text_http_request_data_fail));
                }

            }

        } else {
            if(status == 0){
                showError();
            }else {
                ToastUtils.showShort(_mActivity.getString(R.string.common_text_http_request_data_fail));
            }
        }
    }

    private void showLoading() {
        loadView.setVisibility(View.VISIBLE);
        llLoadingOrFail.setVisibility(View.GONE);
        viewpager.setVisibility(View.INVISIBLE);
        if (isAdded()) {
            ivHint.setImageDrawable(getResources().getDrawable(R.drawable.new_asset_no_assets));
        }
        tvTips.setText(R.string.common_text_loading);
        tvCurrentPage.setText("0");
        tvTotalPage.setText("0");
    }

    private void showError() {
        //眼睛图标跟数量的布局在获取不到数据的时候隐藏掉
        rl_eyeImage_amount.setVisibility(View.GONE);
        llLoadingOrFail.setVisibility(View.VISIBLE);
        if (isAdded()) {
            ivHint.setImageDrawable(getResources().getDrawable(R.drawable.new_assset_loading_fail));
        }
        loadView.setVisibility(View.GONE);
        tvTips.setText(R.string.srl_footer_failed);
        tvCurrentPage.setText("0");
        tvTotalPage.setText("0");
    }

    /**
     * 显示暂无资产图片及提示
     */
    private void showEmptyAsset() {
        //眼睛图标跟数量的布局在获取不到数据的时候隐藏掉
        rl_eyeImage_amount.setVisibility(View.GONE);
        llLoadingOrFail.setVisibility(View.VISIBLE);
        if (isAdded()) {
            ivHint.setImageDrawable(getResources().getDrawable(R.drawable.new_assset_loading_fail));
        }
        loadView.setVisibility(View.GONE);
        tvTips.setText(R.string.star_asset_no_asset);
        tvCurrentPage.setText("0");
        tvTotalPage.setText("0");
    }

    private void showAsset() {
        //眼睛图标跟数量的布局默认显示
        rl_eyeImage_amount.setVisibility(View.VISIBLE);
        viewpager.setVisibility(View.VISIBLE);
        llLoadingOrFail.setVisibility(View.GONE);
        loadView.setVisibility(View.GONE);
    }

    public void refreshData() {
        requestData();
    }

    private static class AssetViewPagerAdapter extends PagerAdapter {

        private Context context;
        private List<TotalAssetBean> assetBeans;
        private String totalPrices;

        public AssetViewPagerAdapter(Context context, List<TotalAssetBean> assetBeans) {
            this.context = context;
            this.assetBeans = assetBeans;
        }

        public void setTotalPrices(String price) {
            this.totalPrices = price;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            View view = View.inflate(context, R.layout.new_asset_fragment_item_total_asset, null);

            TotalAssetBean totalAssetBean = assetBeans.get(position);
            //  TextView tvAmount;
            RoundAngleImageView ivIcon;
            TextView tvAssetName;
            TextView tvRmvRate;
            TextView tvCount;
            TextView tvTotalprice;

            // tvAmount = (TextView) view.findViewById(R.id.tv_amount);
            ivIcon = (RoundAngleImageView) view.findViewById(R.id.iv_icon);
            tvAssetName = (TextView) view.findViewById(R.id.tv_asset_name);
            tvRmvRate = (TextView) view.findViewById(R.id.tv_rmv_rate);
            tvCount = (TextView) view.findViewById(R.id.tv_count);
            tvTotalprice = (TextView) view.findViewById(R.id.tv_totalprice);

            //tvAmount.setText(totalPrices);
            LXGlideImageLoader.getInstance().displayRoundCornerImage(context,
                    ivIcon, totalAssetBean.getAssetIcon(),
                    0, 0, 20);
            if (totalAssetBean.isShowNum()) {
                tvCount.setText(totalAssetBean.getAssetValue());
                tvTotalprice.setText(totalAssetBean.getRmbValue());
            } else {
                tvCount.setText("****");
                tvTotalprice.setText("****");
            }
            tvAssetName.setText(totalAssetBean.getAssetName());
            tvRmvRate.setText(totalAssetBean.getRate());
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String assetName = assetBeans.get(position).getAssetName().toLowerCase();
                    TotalAssetsActivity.start(context, assetName);
                }
            });
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return assetBeans.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            return POSITION_NONE;
        }
    }
}
